package com.example.star.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.entity.ShoppingCart;
import com.example.star.view.activity.PerimeterDetailActivity;
import com.example.star.view.center.ShoppingCartActivity;

import java.util.List;

public class ShoppingCartAdapter extends ArrayAdapter<ShoppingCart> {

    private static final String TAG = "ShoppingCartAdapter";
    private int resource;
    private ShoppingCartActivity activity;

    public ShoppingCartAdapter(Context context, int resource, List<ShoppingCart> shoppingCarts, ShoppingCartActivity activity) {
        super(context, resource, shoppingCarts);
        this.resource = resource;
        this.activity = activity;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(resource, parent, false);
            holder = new ViewHolder();
            holder.checkBox = convertView.findViewById(R.id.checkbox);
            holder.productImageView = convertView.findViewById(R.id.product_image_view);
            holder.productNameTextView = convertView.findViewById(R.id.product_name_text_view);
            holder.productPriceTextView = convertView.findViewById(R.id.product_price_text_view);
            holder.quantityTextView = convertView.findViewById(R.id.quantity_text_view);
            holder.totalPriceTextView = convertView.findViewById(R.id.total_price_text_view);
            holder.increaseButton = convertView.findViewById(R.id.increase_button);
            holder.decreaseButton = convertView.findViewById(R.id.decrease_button);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        ShoppingCart shoppingCart = getItem(position);
        if (shoppingCart != null) {
            bindData(holder, shoppingCart);
            setupCheckbox(holder, shoppingCart);
            setupQuantityButtons(holder, shoppingCart);
        }
        // 添加点击事件
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PerimeterDetailActivity.class);
                // 可以传递商品信息到详情页
                intent.putExtra("starName", shoppingCart.getStarName());
                intent.putExtra("perimeterTitle", shoppingCart.getTitle());
                intent.putExtra("prices", String.valueOf(shoppingCart.getPrices()));
                intent.putExtra("imageResource", shoppingCart.getImageResource());
                intent.putExtra("productType", shoppingCart.getProductType());
                intent.putExtra("freight", shoppingCart.getFreight());
                intent.putExtra("deliveryAddress", shoppingCart.getDeliveryAddress());
                getContext().startActivity(intent);
            }
        });


        return convertView;
    }

    private void bindData(ViewHolder holder, ShoppingCart shoppingCart) {
        holder.productNameTextView.setText(shoppingCart.getTitle());
        holder.productPriceTextView.setText("价格: " + shoppingCart.getPrices() + "元");
        holder.quantityTextView.setText(String.valueOf(shoppingCart.getQuantity()));
        holder.totalPriceTextView.setText("总价:" + shoppingCart.getTotalPrice() + "元");
        loadImage(holder.productImageView, shoppingCart.getImageResource());
    }

    private void setupCheckbox(ViewHolder holder, ShoppingCart shoppingCart) {
        holder.checkBox.setOnCheckedChangeListener(null);
        holder.checkBox.setChecked(shoppingCart.isSelected());
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                shoppingCart.setSelected(isChecked);
                if (activity != null) {
                    activity.updateTotalPrice();
                }
                notifyDataSetChanged();
            }
        });
    }

    private void setupQuantityButtons(ViewHolder holder, ShoppingCart shoppingCart) {
        holder.increaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shoppingCart.setQuantity(shoppingCart.getQuantity() + 1);
                shoppingCart.setTotalPrice(shoppingCart.getPrices() * shoppingCart.getQuantity());
                bindData(holder, shoppingCart);
                if (activity != null) {
                    activity.updateTotalPrice();
                }
                notifyDataSetChanged();
            }
        });

        holder.decreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shoppingCart.getQuantity() > 1) {
                    shoppingCart.setQuantity(shoppingCart.getQuantity() - 1);
                    shoppingCart.setTotalPrice(shoppingCart.getPrices() * shoppingCart.getQuantity());
                    bindData(holder, shoppingCart);
                    if (activity != null) {
                        activity.updateTotalPrice();
                    }
                    notifyDataSetChanged();
                }
            }
        });
    }

    private void loadImage(ImageView imageView, String imageResource) {
        if (imageResource != null) {
            try {
                int imageResId = getContext().getResources().getIdentifier(imageResource, "drawable", getContext().getPackageName());
                if (imageResId != 0) {
                    imageView.setImageResource(imageResId);
                } else {
                    Glide.with(getContext())
                            .load(imageResource)
                            .placeholder(R.drawable.register)
                            .error(R.drawable.register)
                            .into(imageView);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error loading image: " + e.getMessage());
                Glide.with(getContext())
                        .load(imageResource)
                        .placeholder(R.drawable.register)
                        .error(R.drawable.register)
                        .into(imageView);
            }
        }
    }

    private static class ViewHolder {
        CheckBox checkBox;
        ImageView productImageView;
        TextView productNameTextView;
        TextView productPriceTextView;
        TextView quantityTextView;
        TextView totalPriceTextView;
        Button increaseButton;
        Button decreaseButton;
    }
}